#pragma once

#include <iostream>
#include <string>
#include <unordered_map>
#include <functional>
#include "TcpServer.hpp"
#include "HttpProtocol.hpp"

using namespace TcpServerModule;
//const std::string Sep = "\r\n";
//const std::string BlankLine = Sep;
using http_hander_t = std::function<void(HttpRequest&, HttpResponce&)>;

class HttpServer
{
public:
    HttpServer(int port) : _tsvr(std::make_unique<TcpServer>(port))
    {
    }
    void Resgiter(std::string funcname, http_hander_t func)
    {
        _route[funcname] = func;
    }
    bool SafeCheck(const string& service)
    {
        auto iter = _route.find(service);
        return iter != _route.end();
    }
    void Start()
    {
        _tsvr->InitServer([this](SockPtr sockfd, InetAddr client)
                          { return this->HanderHttpRequest(sockfd, client); });
        _tsvr->Loop();
    }
    // 处理http的入口
    bool HanderHttpRequest(SockPtr sockfd, InetAddr client)
    {
        LOG(LogLevel::DEBUG) << "get a new client:" << sockfd->Fd() << " addr info:" << client.Addr();
        std::string http_request;
        sockfd->Recv(&http_request);
        HttpRequest req;
        req.Deserialize(http_request);

        HttpResponce resp;

        //请求可被分为两类， 1.请求一般静态资源 2.提交参数， 携带参数，需要我们进行交互设计
        if(req.IsHasArgs())
        {
            //2 提交参数，携带参数，需要我们进行交互设计
            std::string server = req.GetPath();
            if(SafeCheck(server)) 
                _route[req.GetPath()](req, resp);
            else
                resp.Build(req);
        }
        else
        {
            //1
            //req.Print();
            std::cout<<"------None IsHasArgs()"<<std::endl;
            resp.Build(req);

        }
        std::string resp_str;
        resp.Serialize(&resp_str);
        sockfd->Send(resp_str);


        return true;
    }
    ~HttpServer()
    {
    }

private:
    std::unique_ptr<TcpServer> _tsvr;
    std::unordered_map<std::string, http_hander_t> _route; //功能路由
};
